﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;

public partial class UserControl_ControlSetRouteForTDVFinal : System.Web.UI.UserControl
{
    ClassExecute.ClassExecute dt;
    string str = webapp4U.Configuration.CurrentConnectionString;
    string error = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Request.QueryString["TDV"] != null)
            {

                //nằm trong thread
                ThreadStart thrstar = new ThreadStart(delegate() { LoadInfoTDV(Request.QueryString["TDV"].ToString()); });
                Thread tr = new Thread(thrstar);

                ThreadStart thrstar1 = new ThreadStart(delegate() { LoadKhIsSet(Request.QueryString["TDV"].ToString()); });
                Thread tr1 = new Thread(thrstar1);

                ThreadStart thrstart2 = new ThreadStart(BindTinhThanh);
                Thread tr2 = new Thread(thrstart2);

                ThreadStart thrstart3 = new ThreadStart(BindChannel);
                Thread tr3 = new Thread(thrstart3);

                tr.Start();
                tr1.Start();
                tr2.Start();
                tr3.Start();

                tr.Join();
                tr1.Join();
                tr2.Join();
                tr3.Join();
              
                BindQuanHuyen(DropProvice.SelectedValue.ToString());
                BindSubChannel(DropChannel.SelectedValue);
               
            }
        }
        SendMail();
    }
    protected void DropProvice_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindQuanHuyen(DropProvice.SelectedValue.ToString());
    }
    void BindChannel()
    {
        dt = new ClassExecute.ClassExecute();
        DataTable db = dt.Get_Data_DataTable(str, ref error, "[k_getChannelForSet]", CommandType.StoredProcedure);
        dt.BindDropDownList(db,DropChannel, "ChannelID", "ChannelName");
    }
    void BindSubChannel(string ChannelID)
    {
        dt = new ClassExecute.ClassExecute();
        DataTable db = dt.Get_Data_DataTable(str, ref error, "k_getSubchannel", CommandType.StoredProcedure,
            new SqlParameter("@ChannelID", ChannelID));
        dt.BindDropDownList(db,DropSubChannel, "SubChannelID", "ChannelName");
    }
    protected void imgBtnSave_Click(object sender, ImageClickEventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            CheckBox c;
            
            
            int y = 1;
            for (int i = 0; i < grvCust.Rows.Count; i++)
            {
                c = (CheckBox)grvCust.Rows[i].FindControl("CheckApprove");
                if (c.Checked)
                {

                    Label CustID = (Label)grvCust.Rows[i].FindControl("lblCustID");
                    bool kq = dt.ExecuteSQl_bool(str, CommandType.StoredProcedure, "k_insertSalesRoute", ref error,
                         new SqlParameter("@salesp_key", Request.QueryString["TDV"].ToString()),
                         new SqlParameter("@CustKey", CustID.Text),
                         new SqlParameter("@RecUser", Session["user"].ToString()),
                         new SqlParameter("@i",y));
                    y++;
                   
                }
            }

                //kiểm tra conflict
                DataTable getReturn = dt.Get_Data_DataTable(str, ref error, "[k_checkConflictRoute]", CommandType.StoredProcedure,
                    new SqlParameter("@SalesPKey", Request.QueryString["TDV"].ToString()));
                if (getReturn.Rows.Count > 0)
                {
                    //nếu có thì show dữ liệu
                    grvDup.DataSource = getReturn;
                    grvDup.DataBind();

                    //xóa những thông tin trùng
                    RemoveDuplicated();

                    //Load lại KH đã set
                    LoadKhIsSet(Request.QueryString["TDV"].ToString());

                    TabContainer1.ActiveTabIndex = 2;

                    ShowMessageBox("Bạn đã phân khách hàng trùng với những trình dược viên khác,do đó những khách hàng gắn liền với sản phẩm sau đây sẽ không được lưu vào hệ thống cho : " + lblTDV.Text);



                }
                else
                {
                    grvDup.DataSource = null; ;
                    grvDup.DataBind();
                    ShowMessageBox("Bạn đã phân khách hàng thành công cho TDV: " + lblTDV.Text);
                   
                    LoadKhIsSet(Request.QueryString["TDV"].ToString());
                }
            
        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    protected void ImgBtnNext_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect(webapp4U.Globals.ApplicationPath + "Pages/SetSKUForTDVFinal/Default.aspx?TDV=" + Request.QueryString["TDV"].ToString());
    }
    protected void imgBtnBack_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect(webapp4U.Globals.ApplicationPath + "Pages/SetSKUForTDV/Default.aspx");
    }
    protected void imgBtnDelete_Click(object sender, ImageClickEventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            bool kq = dt.ExecuteSQl_bool(str, CommandType.StoredProcedure, "k_deleteSalesRouteAll", ref error,
                        new SqlParameter("@salesp_key", Request.QueryString["TDV"].ToString()));
            if (kq)
            {
                 //kiểm tra conflict
                DataTable getReturn = dt.Get_Data_DataTable(str, ref error, "[k_checkConflictRoute]", CommandType.StoredProcedure,
                    new SqlParameter("@SalesPKey", Request.QueryString["TDV"].ToString()));
                if (getReturn.Rows.Count > 0)
                {
                    //nếu có thì show dữ liệu
                    grvDup.DataSource = getReturn;
                   
                }
                else
                {

                    grvDup.DataSource = null;
                }
                grvDup.DataBind();
                ShowMessageBox("Nghiệp vụ xóa thành công");
                LoadKhIsSet(Request.QueryString["TDV"].ToString());
            }
        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    void LoadInfoTDV(string salesp_key)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            lblTDV.Text = dt.GetDataDepend(str, "k_getInforTDV", CommandType.StoredProcedure, ref error,
                new SqlParameter("@salesp_key", salesp_key));
        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    void ShowMessageBox(string text)
    {
        MessageBox.Text = text;
        MessageBox.ShowOnPageLoad = true;
    }
    void BindTinhThanh()
    {
        dt = new ClassExecute.ClassExecute();
        DataTable db = dt.Get_Data_DataTable(str, ref error, "k_getTinhThanh", CommandType.StoredProcedure);
        dt.BindDropDownList(db, DropProvice, "MaTinh", "TinhThanh");
    }
    void BindQuanHuyen(string MaTinh)
    {
        dt = new ClassExecute.ClassExecute();
        DataTable db = dt.Get_Data_DataTable(str, ref error, "[k_getQuanHuyenAll]", CommandType.StoredProcedure,
            new SqlParameter("@MaTinh", MaTinh));
        dt.BindDropDownList(db, DropTown, "MaQuan", "QuanHuyen");
    }
    protected void btGetKH_Click(object sender, EventArgs e)
    {
        LoadKH();

    }
    void LoadKH()
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            DataTable db=null;
            if (RadioList.SelectedValue == "0")
            {
                if ((chFilterTinhThanh.Checked) && (chFilterName.Checked!=true))
                {
                    db = dt.Get_Data_DataTable(str, ref error, "[k_getKHForSetUp]", CommandType.StoredProcedure,
                            new SqlParameter("@ProvinceCode", DropProvice.SelectedValue.ToString()),
                            new SqlParameter("@TownCode", DropTown.SelectedValue.ToString()),
                            new SqlParameter("@Sitecode", "FM_00000003"),
                            new SqlParameter("@FilterName","Null"),
                            new SqlParameter("@isNew",chFilterNewCust.Checked),
                            new SqlParameter("@isChannel",chChannel.Checked),
                            new SqlParameter("@SubChannel",DropSubChannel.SelectedValue));
                }
                else if ((chFilterTinhThanh.Checked != true) && (chFilterName.Checked))
                {
                    db = dt.Get_Data_DataTable(str, ref error, "[k_getKHForSetUp]", CommandType.StoredProcedure,
                            new SqlParameter("@ProvinceCode", "Null"),
                            new SqlParameter("@TownCode", "Null"),
                            new SqlParameter("@Sitecode", "FM_00000003"),
                            new SqlParameter("@FilterName", txtNameFilter.Text),
                            new SqlParameter("@isNew", chFilterNewCust.Checked),
                            new SqlParameter("@isChannel",chChannel.Checked),
                            new SqlParameter("@SubChannel",DropSubChannel.SelectedValue));
                }
                else if ((chFilterTinhThanh.Checked) && (chFilterName.Checked))
                {
                    db = dt.Get_Data_DataTable(str, ref error, "[k_getKHForSetUp]", CommandType.StoredProcedure,
                           new SqlParameter("@ProvinceCode", DropProvice.SelectedValue.ToString()),
                            new SqlParameter("@TownCode", DropTown.SelectedValue.ToString()),
                           new SqlParameter("@Sitecode", "FM_00000003"),
                           new SqlParameter("@FilterName", txtNameFilter.Text),
                           new SqlParameter("@isNew", chFilterNewCust.Checked),
                            new SqlParameter("@isChannel", chChannel.Checked),
                            new SqlParameter("@SubChannel", DropSubChannel.SelectedValue));
                }
                else
                {
                    db = dt.Get_Data_DataTable(str, ref error, "[k_getKHForSetUp]", CommandType.StoredProcedure,
                          new SqlParameter("@ProvinceCode", "Null"),
                          new SqlParameter("@TownCode", "Null"),
                          new SqlParameter("@Sitecode", "FM_00000003"),
                          new SqlParameter("@FilterName", "Null"),
                          new SqlParameter("@isNew", chFilterNewCust.Checked),
                           new SqlParameter("@isChannel", chChannel.Checked),
                            new SqlParameter("@SubChannel", DropSubChannel.SelectedValue));
                }
               
            }
            else if (RadioList.SelectedValue == "1")
            {
                if ((chFilterTinhThanh.Checked) && (chFilterName.Checked != true))
                {
                    db = dt.Get_Data_DataTable(str, ref error, "[k_getKHForSetUp]", CommandType.StoredProcedure,
                            new SqlParameter("@ProvinceCode", DropProvice.SelectedValue.ToString()),
                            new SqlParameter("@TownCode", DropTown.SelectedValue.ToString()),
                            new SqlParameter("@Sitecode", "FM_00000002"),
                            new SqlParameter("@FilterName", "Null"),
                           new SqlParameter("@isNew", chFilterNewCust.Checked),
                            new SqlParameter("@isChannel", chChannel.Checked),
                            new SqlParameter("@SubChannel", DropSubChannel.SelectedValue));
                }
                else if ((chFilterTinhThanh.Checked != true) && (chFilterName.Checked))
                {
                    db = dt.Get_Data_DataTable(str, ref error, "[k_getKHForSetUp]", CommandType.StoredProcedure,
                            new SqlParameter("@ProvinceCode", "Null"),
                            new SqlParameter("@TownCode", "Null"),
                            new SqlParameter("@Sitecode", "FM_00000002"),
                            new SqlParameter("@FilterName", txtNameFilter.Text),
                            new SqlParameter("@isNew", chFilterNewCust.Checked),
                             new SqlParameter("@isChannel", chChannel.Checked),
                            new SqlParameter("@SubChannel", DropSubChannel.SelectedValue));
                }
                else if ((chFilterTinhThanh.Checked) && (chFilterName.Checked))
                {
                    db = dt.Get_Data_DataTable(str, ref error, "[k_getKHForSetUp]", CommandType.StoredProcedure,
                           new SqlParameter("@ProvinceCode", DropProvice.SelectedValue.ToString()),
                            new SqlParameter("@TownCode", DropTown.SelectedValue.ToString()),
                           new SqlParameter("@Sitecode", "FM_00000002"),
                           new SqlParameter("@FilterName", txtNameFilter.Text),
                           new SqlParameter("@isNew", chFilterNewCust.Checked),
                            new SqlParameter("@isChannel", chChannel.Checked),
                            new SqlParameter("@SubChannel", DropSubChannel.SelectedValue));
                }
                else
                {
                    db = dt.Get_Data_DataTable(str, ref error, "[k_getKHForSetUp]", CommandType.StoredProcedure,
                          new SqlParameter("@ProvinceCode", "Null"),
                          new SqlParameter("@TownCode", "Null"),
                          new SqlParameter("@Sitecode", "FM_00000002"),
                          new SqlParameter("@FilterName", "Null"),
                          new SqlParameter("@isNew", chFilterNewCust.Checked),
                           new SqlParameter("@isChannel", chChannel.Checked),
                            new SqlParameter("@SubChannel", DropSubChannel.SelectedValue));
                }
            }
            else
            {
                if ((chFilterTinhThanh.Checked) && (chFilterName.Checked != true))
                {
                    db = dt.Get_Data_DataTable(str, ref error, "[k_getKHForSetUp]", CommandType.StoredProcedure,
                            new SqlParameter("@ProvinceCode", DropProvice.SelectedValue.ToString()),
                            new SqlParameter("@TownCode", DropTown.SelectedValue.ToString()),
                            new SqlParameter("@Sitecode", "Null"),
                            new SqlParameter("@FilterName", "Null"),
                            new SqlParameter("@isNew", chFilterNewCust.Checked),
                             new SqlParameter("@isChannel", chChannel.Checked),
                            new SqlParameter("@SubChannel", DropSubChannel.SelectedValue));
                }
                else if ((chFilterTinhThanh.Checked != true) && (chFilterName.Checked))
                {
                    db = dt.Get_Data_DataTable(str, ref error, "[k_getKHForSetUp]", CommandType.StoredProcedure,
                            new SqlParameter("@ProvinceCode", "Null"),
                            new SqlParameter("@TownCode", "Null"),
                            new SqlParameter("@Sitecode", "Null"),
                            new SqlParameter("@FilterName", txtNameFilter.Text),
                            new SqlParameter("@isNew", chFilterNewCust.Checked),
                             new SqlParameter("@isChannel", chChannel.Checked),
                            new SqlParameter("@SubChannel", DropSubChannel.SelectedValue));
                }
                else if ((chFilterTinhThanh.Checked) && (chFilterName.Checked))
                {
                    db = dt.Get_Data_DataTable(str, ref error, "[k_getKHForSetUp]", CommandType.StoredProcedure,
                           new SqlParameter("@ProvinceCode", DropProvice.SelectedValue.ToString()),
                            new SqlParameter("@TownCode", DropTown.SelectedValue.ToString()),
                           new SqlParameter("@Sitecode", "Null"),
                           new SqlParameter("@FilterName", txtNameFilter.Text),
                           new SqlParameter("@isNew", chFilterNewCust.Checked),
                            new SqlParameter("@isChannel", chChannel.Checked),
                            new SqlParameter("@SubChannel", DropSubChannel.SelectedValue));
                }
                else
                {
                    db = dt.Get_Data_DataTable(str, ref error, "[k_getKHForSetUp]", CommandType.StoredProcedure,
                          new SqlParameter("@ProvinceCode", "Null"),
                          new SqlParameter("@TownCode", "Null"),
                          new SqlParameter("@Sitecode", "Null"),
                          new SqlParameter("@FilterName", "Null"),
                         new SqlParameter("@isNew", chFilterNewCust.Checked),
                          new SqlParameter("@isChannel", chChannel.Checked),
                            new SqlParameter("@SubChannel", DropSubChannel.SelectedValue));
                }
            }
            if (db.Rows.Count > 0)
            {
                grvCust.DataSource = db;
            }
            else
            {
                ShowMessageBox("Không tìm thấy khách hàng dựa vào các thông tin tìm kiếm trên");
                grvCust.DataSource = null;
            }
            grvCust.DataBind();
        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    protected void GridCustIsSet_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            if (e.CommandName == "chon")
            {

                GridViewRow grv = ((Control)e.CommandSource).NamingContainer as GridViewRow;

                Label CustID = (Label)grv.FindControl("lblCustID");


                //xóa dữ liệu trong database
                bool kq = dt.ExecuteSQl_bool(str, CommandType.StoredProcedure, "k_DeleteSalesRoute", ref error,
                           new SqlParameter("@salesp_key", Request.QueryString["TDV"].ToString()),
                           new SqlParameter("@CustID", CustID.Text));

                LoadKhIsSet(Request.QueryString["TDV"].ToString());


            }
        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    void LoadKhIsSet(string salesp_key)
    {
         dt = new ClassExecute.ClassExecute();
         try
         {
             DataTable db = dt.Get_Data_DataTable(str, ref error, "[k_GetKHIsSet]", CommandType.StoredProcedure,
                     new SqlParameter("@salesp_key", salesp_key));
             GridCustIsSet.DataSource = db;
             GridCustIsSet.DataBind();
                 
         }
         catch (Exception ex)
         {
             string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
             dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
         }
    }
    void RemoveDuplicated()
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            Label CustID;
            for (int i = 0; i < grvDup.Rows.Count; i++)
            {

                CustID = (Label)grvDup.Rows[i].FindControl("lblCustKey");


                bool kq = dt.ExecuteSQl_bool(str, CommandType.StoredProcedure, "k_deleteSalesRouteDup", ref error,
                          new SqlParameter("@salesp_key", Request.QueryString["TDV"].ToString()),
                          new SqlParameter("@CustKey", CustID.Text));

            }

            LoadKhIsSet(Request.QueryString["TDV"].ToString());
        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    protected void DropChannel_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindSubChannel(DropChannel.SelectedValue);
    }
    void SendMail()
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            DataTable db = dt.Get_Data_DataTable(str, ref error, "[k_checlForSendMailApprove]", CommandType.StoredProcedure);
            
            if (db.Rows.Count > 0)
            {

               //gửi mail
                ClassSendMail newObj=new ClassSendMail();
                newObj.Send_Email("khoi.nguyenhongmanh@gmail.com", "quynhanh.nguyentran@pierre-fabre.vn", "Fimex Sys-Approve Route", "Bạn vui lòng vào hệ thống phần mềm approve cho TDV");

            }
           
           
        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
}